<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" label-width="80px">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="searchForm.gender" placeholder="选择性别" style="width: 120px">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker v-model="searchForm.birthDate" type="date" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="searchForm.classId" placeholder="请选择班级" clearable style="width: 120px">
            <el-option v-for="item in classList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="在读状态" style="width: 120px">
            <el-option label="在读" :value="1" />
            <el-option label="已离开" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="init()">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <!--按钮-->
      <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
        <el-button type="danger" size="medium" icon="el-icon-delete" @click="deleteByIds">批量删除</el-button>
        <el-button type="primary" size="medium" icon="el-icon-plus" @click="openAddDialog">新增学生</el-button>
        <el-button type="success" size="medium" icon="el-icon-download" @click="exportExcel">导出 Excel</el-button>

        <el-upload
          action="/api/student/import"
          :headers="token"
          :show-file-list="false"
          :on-success="handleImportSuccess"
          accept=".xlsx, .xls"
        >
          <el-button type="warning" size="medium" icon="el-icon-upload2">导入 Excel</el-button>
        </el-upload>
      </div>

      <!-- 学生数据表格 -->
      <el-table :data="tableData" border style="width: 100%;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column type="index" label="序号" width="60" :index="indexMethod" align="center" />
        <el-table-column prop="image" label="头像" width="100" align="center">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.image"
              :src="scope.row.image"
              style="width: 50px; height: 50px; border-radius: 50%"
            />
            <el-avatar v-else icon="el-icon-user-solid" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" align="center" />
        <el-table-column prop="gender" label="性别" :formatter="formatGender" align="center" />
        <el-table-column prop="birthDate" label="出生日期" align="center" />
        <el-table-column label="班级" align="center">
          <template slot-scope="scope">
            {{ getClassName(scope.row.classId) }}
          </template>
        </el-table-column>
        <el-table-column prop="joinDate" label="加入班级日期" align="center" />
        <el-table-column prop="status" label="状态" :formatter="formatStatus" align="center" />
        <el-table-column prop="updateTime" label="更新时间" :formatter="formatDateTime" align="center" />
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="selectById(scope.row.id)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!--分页工具条-->
      <el-pagination
        style="margin-top: 20px; text-align: right;"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page.sync="page"
        :page-size="pageSize"
        @current-change="init"
        @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑学生信息" :visible.sync="dialogFormVisible">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="姓名">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model="formData.gender">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :headers="token"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.image" :src="formData.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker v-model="formData.birthDate" type="date" />
        </el-form-item>
        <el-form-item label="班级">
          <el-select
            v-model="formData.classId"
            placeholder="请选择班级"
            style="width: 100%"
          >
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="加入班级日期">
          <el-date-picker
            v-model="formData.joinDate"
            type="date"
            placeholder="请选择加入日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="formData.status">
            <el-option label="在读" :value="1" />
            <el-option label="已离开" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  searchStudents,
  deleteById,
  selectById,
  add,
  update
} from '@/api/student'
import { getToken } from '@/utils/auth'
import { findAll as getAllClasses } from '@/api/class'
import { exportSelectedStudent } from '@/api/export'

export default {
  data() {
    return {
      searchForm: {
        name: '',
        gender: null,
        birthDate: '',
        classId: '',
        status: null
      },
      token: { token: getToken() },
      formData: {},
      tableData: [],
      dialogFormVisible: false,
      page: 1,
      pageSize: 10,
      total: 0,
      classList: []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    getClassName(id) {
      const found = this.classList.find(item => item.id === id)
      return found ? found.name : ''
    },
    indexMethod(index) {
    // 当前页从 1 开始，index 从 0 开始
      return (this.page - 1) * this.pageSize + index + 1
    },
    handleAvatarSuccess(res, file) {
      this.formData.image = res.data
    },
    formatGender(row) {
      return row.gender === 1 ? '男' : row.gender === 2 ? '女' : ''
    },
    formatStatus(row) {
      return row.status === 1 ? '在读' : '已离开'
    },
    formatDateTime(row) {
      return row.updateTime ? row.updateTime.replace('T', ' ') : ''
    },
    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1 // 改页码为第一页
      this.init()
    },

    handleCurrentChange(val) {
      this.page = val
      this.init()
    },

    // 初始化数据
    init() {
      searchStudents({ ...this.searchForm, pageNum: this.page, pageSize: this.pageSize }).then(res => {
        if (res.data.code === 1) {
          this.tableData = res.data.data.records
          this.total = res.data.data.total
        } else {
          this.$message.error(res.data.msg)
        }
      })
      getAllClasses().then(res => {
        if (res.data.code === 1) {
          this.classList = res.data.data
        } else {
          this.$message.error('班级数据加载失败')
        }
      })
    },
    resetForm() {
      this.searchForm = {
        name: '',
        gender: null,
        birthDate: '',
        classId: '',
        status: null
      }
      this.page = 1
      this.init()
    },
    openAddDialog() {
      this.formData = {
        name: '',
        gender: null,
        birthDate: '',
        classId: '',
        joinDate: '',
        status: 1
      }
      this.dialogFormVisible = true
    },
    selectById(id) {
      selectById(id).then(res => {
        if (res.data.code === 1) {
          this.formData = res.data.data
          this.dialogFormVisible = true
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    save() {
      const isUpdate = !!this.formData.id
      const method = isUpdate ? update : add

      method(this.formData).then(res => {
        if (res.data.code === 1) {
          this.$message.success(isUpdate ? '修改成功' : '添加成功')
          this.dialogFormVisible = false
          this.init() // 重新加载数据
        } else {
          this.$message.error(res.data.msg)
        }
      })
      // 添加完成应该刷新一下页面
      this.init()
    },
    deleteById(id) {
      this.$confirm('确定删除该学生？', '提示', {
        type: 'warning'
      }).then(() => {
        deleteById(id).then(res => {
          if (res.data.code === 1) {
            this.$message.success('删除成功')
            this.init()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      })
    },
    deleteByIds() {
      // 1. 先把选中的 id 收集起来
      const ids = this.multipleSelection.map(item => item.id)

      if (ids.length === 0) {
        this.$message.warning('请先选择要删除的学生')
        return
      }

      // 2. 弹出确认框
      this.$confirm('此操作将永久删除所选学生，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 点击确定后执行
          deleteById(ids).then(resp => {
            if (resp.data.code === 1) {
              this.$message.success('批量删除成功')
              this.init() // ✅ 正确方法名
            } else {
              this.$message.error(resp.data.msg)
            }
          })
        })
        .catch(() => {
          // 点击取消后执行
          this.$message.info('已取消批量删除')
        })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    exportExcel() {
      if (!this.multipleSelection.length) {
        this.$message.warning('请先选择需要导出的数据！')
        return
      }

      const ids = this.multipleSelection.map(row => row.id)

      exportSelectedStudent(ids)
        .then(res => {
          const blob = new Blob([res.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })

          const link = document.createElement('a')
          const url = URL.createObjectURL(blob)
          link.href = url
          link.download = '学生信息.xlsx'
          link.style.display = 'none'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          URL.revokeObjectURL(url)
        })
        .catch(err => {
          console.error('导出失败', err)
          this.$message.error('导出失败，请稍后再试！')
        })
    },
    handleImportSuccess(response) {
      this.$message.success('导入成功')
      this.init()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.table-card {
  border-radius: 12px;
  .el-table {
    th {
      background-color: #f5f7fa;
    }
  }
}

.el-card {
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  border-radius: 12px;
  &:hover {
    box-shadow: 0 8px 24px rgba(0,0,0,0.1);
    transform: translateY(-2px);
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}
</style>
